<?php

namespace interface\lzz;

use verify;

class userClass extends index
{
    private string $prefix;
    private string $table;
    private string $tableStaff;

    /**
     * 查找对应的数据库
     */
    private function findDB($creditno): string|null
    {
        $info = query('`saas.admin`.`company` ', " TIN = '$creditno'", 'prefix');
        if (empty($info['prefix'])) {
            return null;
        }
        return $info['prefix'];
    }

    /**
     * 参数检测
     */
    private function check($field): string|bool
    {
        if ($this->checkSign($field) !== true) {
            return $this->checkSign($field);
        } else {
            $prefix = self::findDB($field['creditno']);
            if (empty($prefix)) {
                return '纳税人识别码 对应企业不存在';
            } else {
                $this->prefix     = $prefix;
                $this->table      = " `saas.$prefix`.`user` ";
                $this->tableStaff = " `saas.$prefix`.`staff` ";
                return true;
            }
        }
    }

    /**
     * 获取用户
     */
    function list(): void
    {
        $field      = [
            'creditno' => $this->post('creditno'),
            'status'   => $this->post('status') !== null ? $this->post('status') : 1,
        ];
        $annotation = [
            'creditno' => '纳税人识别码',
            'status'   => '用户状态',
        ];
        $rules      = [
            'creditno' => 'required',
            'status'   => 'required',
        ];
        // 校验是否符合规则
        $vt     = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
        } else {
            $warn = self::check($field);
            if ($warn !== true) {
                $this->resp['warn'] = $warn;
            } else {
                $state              = $field['status'] == 1 ? '启用' : '停用';
                $page               = $this->page([
                    "table" => $this->table,
                    'where' => " state = '$state' ",
                    'field' => 'userName, name',
                    "order" => "time desc"
                ]);
                $data['array']      = $page['array'];
                $data['para']       = $page['para'];
                $this->code         = 1;
                $this->resp['data'] = $data;
            }
        }
    }

    /**
     * 创建账户
     * @return void
     */
    public function create(): void
    {
        $field      = [
            'userName' => $this->post('userName'),
            'name'     => $this->post('name'),
            'tel'      => $this->post('tel'),
            'creditno' => $this->post('creditno'),
            'levelnum' => $this->post('levelnum'),
        ];
        $annotation = [
            'userName' => '帐号用户名',
            'name'     => '姓名',
            'tel'      => '手机号',
            'creditno' => '纳税人识别码',
            'levelnum' => '用户等级',
        ];
        $rules      = [
            'userName' => 'required',
            'creditno' => 'required',
            'levelnum' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
        } else {
            $warn = self::check($field);
            if ($warn !== true) {
                $this->resp['warn'] = $warn;
            } else {
                $levelnum = $field['levelnum'];
                $userName = $field['userName'];
                $where    = " userName = '$userName' ";
                $users    = query($this->table, generateWhere(['userName' => $userName]));
                unset($field['levelnum'], $field['creditno']);
                if ($field['tel']) {
                    if (sqlNum($this->table, " tel = '$field[tel]' and userName <> '$userName' ") > 0) {
                        $this->resp['warn'] = "已有此号码信息的账户信息";
                        goto  resp;
                    }
                }

                if (empty($users['uid'])) {
                    if ($levelnum == 1) {
                        $role  = '["l507vztyyrk4"]';
                        $isDel = 1;
                    } else {
                        $role  = '["visitor"]';
                        $isDel = 0;
                    }
                    //	写入用户
                    $stid   = static::getId();
                    $userNo = 'YRSQ_' . strtoupper(substr(md5(uniqid()), 0, 14));
                    // 写入用户表
                    $warn    = static::insert([
                        "table" => $this->table,
                        'field' => array_merge([
                            'uid'      => self::getNo(),
                            'stid'     => $stid,
                            'userNo'   => $userNo,
                            'role'     => $role,
                            'password' => md5s('lzz123456'),
                            'operator' => 'system',
                            'state'    => '启用',
                            'isDel'    => $isDel,
                            'time'     => $this->time,
                        ], $field),
                    ], false);
                    $orderNo = 'YKXX_' . strtoupper(substr(md5(uniqid()), 0, 14));
                    //	写入员工信息表
                    self::insert([
                        'table' => $this->tableStaff,
                        'field' => [
                            'stid'     => $stid,
                            'orderNo'  => $orderNo,
                            'name'     => $field['name'],
                            'state'    => '转正',
                            'workFlow' => '已复核',
                            'ico'      => 'img/websiteImg/replaceHead.jpg',
                            'time'     => $this->time,
                        ],
                    ], false);
                } else {
                    unset($field['userName']);
                    $warn = static::update([
                        "table" => $this->table,
                        'field' => $field,
                        'where' => $where,
                    ], false);

                    static::update([
                        "table" => $this->tableStaff,
                        'field' => $field,
                        'where' => " stid = '$users[stid]' ",
                    ], false);

                }

                if (!in_array($warn, ['更新成功', '新增成功'])) {
                    $this->resp['warn'] = $warn;
                } else {
                    $this->code         = 1;
                    $this->resp['data'] = [
                        'userName' => $userName,
                        'name'     => $field['name']
                    ];
                }
            }
        }
        resp:
    }

    /**
     * 修改状态
     * @return void
     */
    public function modify(): void
    {
        $field      = [
            'userName' => $this->post('userName'),
            'creditno' => $this->post('creditno'),
            'status'   => $this->post('status'),
        ];
        $annotation = [
            'userName' => '帐号用户名',
            'creditno' => '纳税人识别码',
            'status'   => '用户状态',
        ];
        $rules      = [
            'userName' => 'required',
            'creditno' => 'required',
            'status'   => 'required',
        ];
        // 校验是否符合规则
        $vt     = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
        } else {
            $warn = self::check($field);
            if ($warn !== true) {
                $this->resp['warn'] = $warn;
            } else {
                $where = " userName = '{$field['userName']}' ";
                $user  = query($this->table, $where);
                if (empty($user['uid'])) {
                    $this->resp['warn'] = '用户信息不存在';
                } elseif ($user['isDel'] == 1) {
                    $this->resp['warn'] = '该用户为主账号无法停用';
                } else {
                    $warn = static::update([
                        "table" => $this->table,
                        'field' => [
                            'state' => $field['status'] == 1 ? '启用' : '停用'
                        ],
                        'where' => $where,
                    ], false);
                    if ($warn == '更新成功') {
                        $this->resp['warn'] = '操作成功';
                        $this->code         = 1;
                    }
                }
            }
        }
    }

    /**
     * 删除账户
     * @return void
     */
    public function delete(): void
    {
        $field      = [
            'userName' => $this->post('userName'),
            'creditno' => $this->post('creditno'),
        ];
        $annotation = [
            'userName' => '帐号用户名',
            'creditno' => '纳税人识别码',
        ];
        $rules      = [
            'userName' => 'required',
            'creditno' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
        } else {
            $warn = self::check($field);
            if ($warn !== true) {
                $this->resp['warn'] = $warn;
            } else {
                $where = " userName = '{$field['userName']}' ";
                $user  = query($this->table, $where);
                if (empty($user['uid'])) {
                    $this->resp['warn'] = '用户信息不存在';
                } elseif ($user['isDel'] == 1) {
                    $this->resp['warn'] = '该用户为主账号无法删除';
                } else {
                    $warn = delete(["table" => $this->table, "where" => $where]);
                    if ($warn == '删除成功') {
                        delete(["table" => $this->tableStaff, "where" => " stid = '$user[stid]' "]);
                        $this->resp['warn'] = $warn;
                        $this->code         = 1;
                    }
                }
            }
        }
    }

    /**
     * 登录
     * @return void
     */
    public function login(): void
    {
        $field      = [
            'userName' => $this->post('userName'),
            'creditno' => $this->post('creditno'),
        ];
        $annotation = [
            'userName' => '帐号用户名',
            'creditno' => '纳税人识别码',
        ];
        $rules      = [
            'userName' => 'required',
            'creditno' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
        } else {
            $warn = self::check($field);
            if ($warn !== true) {
                $this->resp['warn'] = $warn;
            } else {
                $uid = query($this->table, " userName = '$field[userName]' ")['uid'];
                if (empty($uid)) {
                    $this->resp['warn'] = '用户信息不存在';
                } else {
                    $this->code         = 1;
                    $this->resp['warn'] = '登录成功';
                    $token              = md5($uid . '_' . time());
                    static::rSet($token, $uid); 
                    static::rSet($uid . '_table', $this->table);
                    $this->resp['data'] = 'https://' . $this->prefix . '.saas.yumukeji.com/interface/v1/?cla=loginApp&fun=redirect&rk='.redisKey.'&token=' . $token;
                }
            }
        }
    }

}
